package com.warom.sdg.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 智慧粮仓设备管理器
 * 提供高级接口，用于管理智慧粮仓设备
 */
public class GranaryDeviceManager {
    private static final String TAG = "GranaryDeviceManager";
    
    // 线程池
    private static final Executor executor = Executors.newFixedThreadPool(3);
    
    // 主线程Handler
    private static final Handler mainHandler = new Handler(Looper.getMainLooper());
    
    // 单例实例
    private static GranaryDeviceManager instance;
    
    // 上下文引用
    private WeakReference<Context> contextRef;
    
    /**
     * 截图响应回调接口
     */
    public interface ScreenshotCallback {
        void onSuccess(Bitmap originalImage, Bitmap annotatedImage, List<PestDetectionHelper.PestDetectionResult> pestResults);
        void onFailure(Exception e);
    }
    
    /**
     * 直播地址回调接口
     */
    public interface LiveStreamCallback {
        void onSuccess(String liveStreamUrl);
        void onFailure(Exception e);
    }
    
    /**
     * 设备唤醒回调接口
     */
    public interface WakeupCallback {
        void onSuccess();
        void onFailure(Exception e);
    }
    
    /**
     * 私有构造函数
     * @param context 上下文
     */
    private GranaryDeviceManager(Context context) {
        this.contextRef = new WeakReference<>(context.getApplicationContext());
    }
    
    /**
     * 获取单例实例
     * @param context 上下文
     * @return 智慧粮仓设备管理器实例
     */
    public static synchronized GranaryDeviceManager getInstance(Context context) {
        if (instance == null) {
            instance = new GranaryDeviceManager(context);
        }
        return instance;
    }
    
    /**
     * 初始化设备管理器
     * @param appKey API应用Key
     * @param appSecret API应用Secret
     */
    public void init(String appKey, String appSecret) {
        Context context = contextRef.get();
        if (context != null) {
            OpenApiClient.init(context, appKey, appSecret);
        }
    }
    
    /**
     * 获取直播地址
     * @param deviceId 设备ID
     * @param channel 通道号
     * @param isHighDefinition 是否高清（true:高清，false:标清）
     * @param expireHours 有效期小时数
     * @param callback 回调接口
     */
    public void getLiveStreamUrl(final String deviceId, final int channel, 
                              final boolean isHighDefinition, final int expireHours, 
                              final LiveStreamCallback callback) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 计算过期时间（当前时间 + 有效期小时数）
                    long expireTime = System.currentTimeMillis() + expireHours * 60 * 60 * 1000L;
                    
                    // 调用API获取直播地址
                    String streamUrl = OpenApiClient.getLiveStream(
                            deviceId,
                            channel,
                            isHighDefinition ? 0 : 1,  // 0:高清, 1:标清
                            expireTime
                    );
                    
                    // 返回结果到主线程
                    final String finalUrl = streamUrl;
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (finalUrl != null) {
                                callback.onSuccess(finalUrl);
                            } else {
                                callback.onFailure(new Exception("获取直播地址失败"));
                            }
                        }
                    });
                } catch (final Exception e) {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure(e);
                        }
                    });
                }
            }
        });
    }
    
    /**
     * 获取直播地址（带更多选项）
     * @param deviceId 设备ID
     * @param channel 通道号
     * @param isHighDefinition 是否高清（true:高清，false:标清）
     * @param expireHours 有效期小时数
     * @param protocol 协议类型
     * @param videoCode 视频编码
     * @param callback 回调接口
     */
    public void getLiveStreamUrl(final String deviceId, final int channel, 
                              final boolean isHighDefinition, final int expireHours, 
                              final String protocol, final String videoCode,
                              final LiveStreamCallback callback) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 计算过期时间（当前时间 + 有效期小时数）
                    long expireTime = System.currentTimeMillis() + expireHours * 60 * 60 * 1000L;
                    
                    // 调用API获取直播地址
                    String streamUrl = OpenApiClient.getLiveStream(
                            deviceId,
                            channel,
                            isHighDefinition ? 0 : 1,  // 0:高清, 1:标清
                            expireTime,
                            protocol,
                            videoCode
                    );
                    
                    // 返回结果到主线程
                    final String finalUrl = streamUrl;
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (finalUrl != null) {
                                callback.onSuccess(finalUrl);
                            } else {
                                callback.onFailure(new Exception("获取直播地址失败"));
                            }
                        }
                    });
                } catch (final Exception e) {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure(e);
                        }
                    });
                }
            }
        });
    }
    
    /**
     * 唤醒设备
     * @param deviceId 设备ID
     * @param channel 通道号
     * @param callback 回调接口
     */
    public void wakeupDevice(final String deviceId, final int channel, final WakeupCallback callback) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    final boolean success = OpenApiClient.wakeupDevice(deviceId, channel);
                    
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (success) {
                                callback.onSuccess();
                            } else {
                                callback.onFailure(new Exception("设备唤醒失败"));
                            }
                        }
                    });
                } catch (final Exception e) {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure(e);
                        }
                    });
                }
            }
        });
    }
    
    /**
     * 获取设备截图（不进行害虫识别）
     * @param deviceId 设备ID
     * @param channel 通道号
     * @param callback 回调接口
     */
    public void getDeviceScreenshot(final String deviceId, final int channel, final ScreenshotCallback callback) {
        getDeviceScreenshot(deviceId, channel, false, callback);
    }
    
    /**
     * 获取设备截图
     * @param deviceId 设备ID
     * @param channel 通道号
     * @param detectPests 是否进行害虫识别
     * @param callback 回调接口
     */
    public void getDeviceScreenshot(final String deviceId, final int channel, 
                                 final boolean detectPests, final ScreenshotCallback callback) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 调用API获取截图
                    final OpenApiClient.ScreenshotResult result = OpenApiClient.getDeviceScreenshot(
                            deviceId,
                            channel,
                            detectPests ? 2 : 1  // 1:不识别, 2:识别
                    );
                    
                    if (result == null || result.image == null) {
                        mainHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                callback.onFailure(new Exception("获取设备截图失败"));
                            }
                        });
                        return;
                    }
                    
                    // 处理截图结果
                    PestDetectionHelper.loadAndAnnotateImageAsync(
                            result.image,
                            result.pests,
                            new PestDetectionHelper.AnnotatedImageLoadCallback() {
                                @Override
                                public void onAnnotatedImageLoaded(
                                        final Bitmap bitmap, 
                                        final List<PestDetectionHelper.PestDetectionResult> results) {
                                    
                                    // 加载原始图像
                                    PestDetectionHelper.loadImageAsync(
                                            result.image,
                                            new PestDetectionHelper.ImageLoadCallback() {
                                                @Override
                                                public void onImageLoaded(final Bitmap originalBitmap) {
                                                    mainHandler.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            callback.onSuccess(originalBitmap, bitmap, results);
                                                        }
                                                    });
                                                }
                                                
                                                @Override
                                                public void onImageLoadFailed(final Exception e) {
                                                    mainHandler.post(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            // 原图加载失败，但标注图成功，仍返回标注图
                                                            callback.onSuccess(null, bitmap, results);
                                                        }
                                                    });
                                                }
                                            });
                                }
                                
                                @Override
                                public void onImageLoadFailed(final Exception e) {
                                    mainHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            callback.onFailure(e);
                                        }
                                    });
                                }
                            });
                    
                } catch (final Exception e) {
                    mainHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            callback.onFailure(e);
                        }
                    });
                }
            }
        });
    }
} 